package com.anghui.demo.handler;

import com.anghui.demo.vo.response.R;
import com.anghui.demo.domain.handler.ServiceException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理自定义业务异常
    @ExceptionHandler(ServiceException.class)
    public R handleServiceException(ServiceException ex) {
        ex.printStackTrace();
        return R.fail(500, ex.getMessage());
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidationExceptions(MethodArgumentNotValidException ex) {
        ex.printStackTrace();
        String errorMessage = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(error -> error.getDefaultMessage())
                .collect(Collectors.joining("; "));
        return R.fail(400, errorMessage);
    }

    // 处理所有未捕获的异常
    @ExceptionHandler(Exception.class)
    public R handleAllExceptions(Exception ex) {
        ex.printStackTrace();
        return R.fail(501, ex.getMessage());
    }
}